<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class login_hook {
	var $CI;
	var $valid = array('login');
	var $ajax;
	var $upload;
	
	function __construct(){
        $this->CI =& get_instance();
		$this->ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
		$this->upload = !empty ($_FILES);
    }

	public function do_check_login() {
		$controller = $this->CI->uri->segment(1);
		$login = $this->CI->session->userdata('validated');
		if( !$login && !in_array($controller, $this->valid)) {
            if($this->ajax) 
				exit(json_encode(array('err' => -1, 'msg' => "Not authenticated")));
			else
				redirect('login');
        } else if (!in_array($controller, $this->valid) && !$this->ajax && !$this->upload) {
			$currUser = $this->CI->session->userdata('currUser');
	        $data = array(
						'active' => $controller,
						'id' => $currUser['id'],
	                    'f_name' => $currUser['f_name'],
	                    'l_name' => $currUser['l_name'],
	                    'user' => $currUser['user'],
	                    'email' => $currUser['email'],
						'role' => $currUser['role']
	                );
	        $this->CI->load->view('header', $data);
		}
	}
	
	public function do_load_footer() {
		$controller = $this->CI->uri->segment(1);
		if (!in_array($controller, $this->valid) && !$this->ajax && !$this->upload) {
			$this->CI->load->view('footer', array('controller' => $controller));
		}
	}
}